-module(check_deals).

%%
%% Include files
%%
-include("database.hrl").
-include_lib("stdlib/include/qlc.hrl").
%%
%% Exported Functions
%%

-export([submit_ask/4, submit_bid/4, validate_ask_deal/3 , validate_bid_deal/3,total_money/2,
		 remove_bid/1, update_bid/3,add_to_favorite/2,remove_from_favorite/2,t/0,update_ask/3,add_new_user/2]).


%-----------------------------------------------------------------------------------------------------------------%
%---										add new user 
%-----------------------------------------------------------------------------------------------------------------%
add_new_user(UserId,UserName)->
	User = do(qlc:q([C||C<-mnesia:table(users),C#users.id==UserId])),
	case User of 
		([])->NewUser=#users{id=UserId,name= UserName, money=10000, profit=0, value=0},
			  insert_to_DB(NewUser),
			  total_profit(UserId),
  	 			total_value(UserId);
		(_)->ok
	end.


%-----------------------------------------------------------------------------------------------------------------%
%---										add to favorite 
%-----------------------------------------------------------------------------------------------------------------%
add_to_favorite(UserId,StockId)->
	Favorite= do(qlc:q([C||C<-mnesia:table(favorites),C#favorites.stock_id==StockId,
							 C#favorites.user_id==UserId ])),
	case Favorite of
		([])-> 
			Key=get_new_key(favorite_counter),
			NewFavorite=#favorites{id=Key,stock_id=StockId,user_id=UserId},
			insert_to_DB(NewFavorite);
		(_)->ok
	end.

%-----------------------------------------------------------------------------------------------------------------%
%---										remove from favorite 
%-----------------------------------------------------------------------------------------------------------------%
remove_from_favorite(UserId,StockId)->
	io:format("remove favorite: User ~p Stock ~p ~n",[UserId,StockId]),
	Favorite= do(qlc:q([C||C<-mnesia:table(favorites),C#favorites.stock_id==StockId,
							 C#favorites.user_id==UserId ])),
	io:format("remove favorite: ~p ~n",[Favorite]),
	case Favorite of 
		
		([H|T])->
			Key=H#favorites.id,
			io:format("Key: ~p ~n",[Key]),
			remove_from_db(favorites, Key);
		(_)-> ok
	end.

%-----------------------------------------------------------------------------------------------------------------%
%---										setStckValue
%-----------------------------------------------------------------------------------------------------------------%
setStockValue(StockID,DealVal,NumOfStocks)->
	%we call this function in any deal, once: in updateportfolio: with the stock id and the price deal
  	[Company] = do(qlc:q([C||C<-mnesia:table(company_stocks),C#company_stocks.id==StockID ])),
	io:format("setStockValue: Company: ~p ~n ", [Company]),
	CurrDealWeight = Company#company_stocks.last_weight,
	TransactionPercent = (NumOfStocks /Company#company_stocks.total_exist)*100,
	DealWeight  =  (DealVal)*TransactionPercent ,
	DealCountBefor = Company#company_stocks.dealsCountCounter,
	%io:format("setStockValue: StockId: ~p Price: ~p DealWeight: ~p ~n ", [StockID, DealVal, DealWeight]),
	%io:format("setStockValue: DealCountBefor: ~p ~n ", [DealCountBefor]),
	%io:format("setStockValue: ?MaxDealsForValue ~p ~n ", [?MaxDealsForValue]),
	%update currVal : Max price from the last MaxDealsForValue deals done with this  company stocks 
	%if we get to the MaxDealsForValue we start and count again and set the currVal to be 
		%the avareg of the companyVal when she got in to this market and the last CurrVal
	
	if (Company#company_stocks.dealsCountCounter == ?MaxDealsForValue) ->%Company.StockVal = CompanyVal+*CurrVal/2
	%	   	io:format("setStockValue: dealsCountCounter == ?MaxDealsForValue ~n "),
			NewVal=(Company#company_stocks.current_value+Company#company_stocks.company_val)/2,		 
 	%		io:format("setStockValue: NewVal ~p ~n ",[NewVal]),
		   	DealCounCurrUpdate=Company#company_stocks{dealsCountCounter=0,current_value=NewVal,last_weight=0},		
			insert_to_DB(DealCounCurrUpdate);					
	
	   ((DealWeight>CurrDealWeight) and  (Company#company_stocks.dealsCountCounter<?MaxDealsForValue)) ->
	%	  io:format("setStockValue: DealVal>CurrVal & dealsCountCounter< ?MaxDealsForValue ~n "),
						DealCurrUpdate=Company#company_stocks{dealsCountCounter=DealCountBefor+1,current_value=DealVal,last_weight=DealWeight},		
						insert_to_DB(DealCurrUpdate);				
		((DealWeight=<CurrDealWeight) and  (Company#company_stocks.dealsCountCounter<?MaxDealsForValue))->
	%	  io:format("setStockValue: DealVal<CurrVal & dealsCountCounter == ?MaxDealsForValue ~n "),
						DealCountUpdate=Company#company_stocks{dealsCountCounter=DealCountBefor+1},		
						insert_to_DB(DealCountUpdate)
				
	end.



%-----------------------------------------------------------------------------------------------------------------%
%---										remove_ask
%-----------------------------------------------------------------------------------------------------------------%
remove_ask(AskId)->
	remove_from_db(ask_queue,AskId).


%-----------------------------------------------------------------------------------------------------------------%
%---										update_ask
%-----------------------------------------------------------------------------------------------------------------%
update_ask(AskId, Amount, Value)->
	%io:format(" update_ask - ASk:~p~n",[AskId]),
	[Ask]=  do(qlc:q([X||X<-mnesia:table(ask_queue),
				 		X#ask_queue.ask_id==AskId 
					    ])),
	%io:format("BID:~p~n",[Bid]),
	
	NewAsk=Ask#ask_queue{amount=(Amount), price=(Value)},
	io:format("new ASK:~p~n",[NewAsk]),
	insert_to_DB(NewAsk).




%LLLLLLLLLLLLLLLLLLLLLLl

%-----------------------------------------------------------------------------------------------------------------%
%---										remove_bid
%-----------------------------------------------------------------------------------------------------------------%
remove_bid(BidId)->
	remove_from_db(bid_queue,BidId).


%-----------------------------------------------------------------------------------------------------------------%
%---										update_bid
%-----------------------------------------------------------------------------------------------------------------%
update_bid(BidId, Amount, Value)->
	%io:format(" update_bid - BID:~p~n",[BidId]),
	[Bid]=  do(qlc:q([X||X<-mnesia:table(bid_queue),
				 		X#bid_queue.bid_id==BidId 
					    ])),
	%io:format("BID:~p~n",[Bid]),
	
	NewBid=Bid#bid_queue{amount=(Amount), price=(Value)},
	%io:format("new BID:~p~n",[NewBid]),
	insert_to_DB(NewBid).


%-----------------------------------------------------------------------------------------------------------------%
%---										submit_bid
%-----------------------------------------------------------------------------------------------------------------%
submit_bid(UserID, Stockid, Amount, Price)->
		
	Valid = validate_bid_deal(UserID, Stockid, Amount),
	if (Valid==false)->false;
	   (Valid==true)->
			Res1= do(qlc:q([X||X<-mnesia:table(ask_queue),X#ask_queue.price >= Price,X#ask_queue.stock_id==Stockid])),
			%x in table and his price%
			
			Fun = fun(Elem1, Elem2) -> 
				if Elem1#ask_queue.price > Elem2#ask_queue.price ->false;
					Elem1#ask_queue.price =< Elem2#ask_queue.price->true
				end
			end,
    	%io:format("befor sorting ~p~n",[Res1]),	
		Res=lists:sort(Fun, Res1),
    	%io:format("Fit Asks: ~p~n",[Res]),
	
		check_bid_deal(UserID, Stockid, Amount, Price, Res)
	end.

%-----------------------------------------------------------------------------------------------------------------%
%---								check_bid_deal
%-----------------------------------------------------------------------------------------------------------------%
check_bid_deal(UserID, Stockid, Amount, Price, Res)->
	io:format("BID Deal: Amount: ~p Price: ~p ~nRes: ~p ~n ", [Amount, Price, Res]),
	case Res of%IF NO aSK FIT- insert new bid 
		[] ->
			%io:format("empty~n", []),
			if Amount>0 ->%insert to bid q the new bid
				 Bid =#bid_queue{bid_id=get_new_key(bid_counter),
								 user_id=UserID, 
								 stock_id=Stockid, 
								 amount=Amount, 
								 price=Price},
				% io:format("new bid id ~p~n", [Bid#bid_queue.bid_id]),
				 insert_to_DB(Bid);
			  Amount==0->ok
			end;
		[Head|Next]-> 
			BuyerId= Head#ask_queue.user_id,%the one that set ask
			SellerId= UserID,%the one that set bid
			%io:format("BuyerId ~p SellerId~p ~n", [BuyerId,SellerId]),
			%io:format("head next~n", []),
			
			if Amount > Head#ask_queue.amount  ->% need to insert new bid or to check for other asks
				    %io:format("amount>head !!! ~p ~p ~n", [Amount,Head#ask_queue.amount]),
				    remove_from_db(ask_queue,Head#ask_queue.ask_id),
					update_portfolio(BuyerId, Stockid,Head#ask_queue.amount, Price, 1),
					update_portfolio(SellerId,Stockid,  Head#ask_queue.amount, Price, 0),				   
				    check_bid_deal(UserID, Stockid, (Amount- (Head#ask_queue.amount) ), Price, Next);
			   
			   Amount==Head#ask_queue.amount ->
				   %somone set bid that have ask with same stocks to ask so no  need to insert to bid q !!!!!
				   %need to remove from ask q!!!!
				   %	io:format("amount==head !!! ~p ~p ~n", [Amount,Head#ask_queue.amount]),
					remove_from_db(ask_queue,Head#ask_queue.ask_id),
			   		update_portfolio(BuyerId, Stockid, Amount, Price, 1),
					update_portfolio(SellerId,Stockid, Amount, Price, 0);
			   
			   Amount < Head#ask_queue.amount->
				  %somone set bid that have ask with more stocks to ask so no  need to insert to bid q !!!!!
				  %need to remove from ask and set new ask
				 	%io:format("amount<head !!! ~p ~p ~n", [Amount,Head#ask_queue.amount]),
					%io:format("head !!!  ~p ~n", [Head]),			
					NewAsk=Head#ask_queue{amount=(Head#ask_queue.amount-Amount)},
					%io:format("NewAsk:______ ~p  ~n", [NewAsk]),
					insert_to_DB(NewAsk),
					
					update_portfolio(BuyerId, Stockid, Amount, Price, 1),
						% the player that buy stocks
							%take the current value from stock company
							%insert to stock table the record- 
							%update profit -add just profit of this stock  
							%update value -add just value of this stock
							%update money
					
					
					update_portfolio(SellerId,Stockid, Amount, Price, 0)
						% the player that sell stocks
							%maybe more then one record for this stock!!!--> then update total in other fun
							%update stock table record - total: if total==0 then remove from stock table: 
							%update profit -add just profit of this stock  
							%update value -add just value of this stock
							%update money
		
			end;
			
		_ -> ok
	end.
%-----------------------------------------------------------------------------------------------------------------%
%---					validate_bid_deal
%-----------------------------------------------------------------------------------------------------------------%
validate_bid_deal(UserID, StockID, Amount)->
	%io:format("validate_bid_deal~n"),
	StockTableList=do(qlc:q([X||X<-mnesia:table(user_stock_table),
				 X#user_stock_table.user_id == UserID,X#user_stock_table.stock_id == StockID])),
	case StockTableList of
		[] -> false;
		_ -> validate_numOf_stock(StockTableList,Amount)
	end.			 
validate_numOf_stock(StockTableList,Amount)->
	%io:format("StockTable Exist: ~p Amount ~p ~n",[StockTableList,Amount]),
	case StockTableList of
		([H|T])-> if (H#user_stock_table.total>=Amount)->true;
				     (H#user_stock_table.total<Amount)->validate_numOf_stock(T,Amount-H#user_stock_table.total)
				 end;
		([H|[]])->if (H#user_stock_table.total>=Amount)->true;
					(H#user_stock_table.total<Amount)->false
				end;	
		([])->false
	end.	
%-----------------------------------------------------------------------------------------------------------------%
%---							submit_ask
%-----------------------------------------------------------------------------------------------------------------%
submit_ask(UserID, Stockid, Amount, Price)->
	Valid = validate_ask_deal(UserID, Amount, Price),
	if (Valid==false)->false;
	   (Valid==true)->
			Res1= do(qlc:q([X||X<-mnesia:table(bid_queue),
					X#bid_queue.price =< Price,X#bid_queue.stock_id==Stockid])),%x in table and his price%	
			Fun = fun(Elem1, Elem2) -> 
				  if Elem1#bid_queue.price > Elem2#bid_queue.price ->
						false;
					Elem1#bid_queue.price =< Elem2#bid_queue.price->
						true
				  end
		  	end,
    		%io:format("befor sorting ~p~n",[Res1]),
	
			Res=lists:sort(Fun, Res1),
			%io:format("after sorting ~p~n",[Res]),
			check_ask_deal(UserID, Stockid, Amount, Price, Res)
	end.
	

%-----------------------------------------------------------------------------------------------------------------%
%---								check_ask_deal
%-----------------------------------------------------------------------------------------------------------------%
check_ask_deal(UserID, Stockid, Amount, Price, Res)->	
	io:format("Ask deal: Amount: ~p Price: ~p ~nRes: ~p ~n ", [Amount, Price, Res]),
	case Res of% when no bid deal fit
		[] ->
			%io:format("empty~n", []),
			if Amount>0 ->%insert to ask q the new ask
				 Ask =#ask_queue{ask_id=get_new_key(ask_counter),
								 user_id=UserID, 
								 stock_id=Stockid, 
								 amount=Amount, 
								 price=Price},
				%io:format("ask id ~p~n", [Ask#ask_queue.ask_id]),
				 %io:format("2~n", []),
				 insert_to_DB(Ask);
			  Amount==0->ok
			end;
		[Head|Next]-> 
			
			BuyerId= UserID,%the one that set ask
			SellerId= Head#bid_queue.user_id ,%the one that set bid
			%io:format("BuyerId ~p SellerId~p ~n", [BuyerId,SellerId]),

			if Amount > Head#bid_queue.amount  ->
				   NumOFLeftAsKStock = Amount- Head#bid_queue.amount,
				   %io:format("amount>head !!! ~p ~p ~n", [Amount,Head#bid_queue.amount]),
				   remove_from_db(bid_queue,Head#bid_queue.bid_id),
				   update_portfolio(BuyerId,Stockid, Head#bid_queue.amount, Price, 1),
				   update_portfolio(SellerId,Stockid, Head#bid_queue.amount, Price, 0),
				   check_ask_deal(UserID, Stockid, NumOFLeftAsKStock, Price, Next);
			   
			   Amount==Head#bid_queue.amount ->
				   	%io:format("amount==head !!! ~p ~p ~n", [Amount,Head#bid_queue.amount]),
					remove_from_db(bid_queue,Head#bid_queue.bid_id),
					update_portfolio(BuyerId,Stockid, Amount, Price, 1),
					update_portfolio(SellerId,Stockid, Amount, Price, 0);
				   	
			  
			   Amount < Head#bid_queue.amount->		
				  	NumOfAsk=Head#bid_queue.amount-Amount,
					%io:format("amount<head !!! ~p ~p ~n", [Amount,Head#bid_queue.amount]),
					Bid =Head#bid_queue{ amount=(NumOfAsk)},
				 	insert_to_DB(Bid),
					update_portfolio(BuyerId,Stockid,Amount, Price, 1),
					update_portfolio(SellerId,Stockid, Amount, Price, 0)					  
			end;
			
		_ -> ok
	end.

%-----------------------------------------------------------------------------------------------------------------%
%---								validate_ask_deal
%-----------------------------------------------------------------------------------------------------------------%
validate_ask_deal(UserID, Amount, Price)->
	%io:format("userid=~p~n",[UserID]),
	[User]=do(qlc:q([X||X<-mnesia:table(users),
				 X#users.id == UserID])),
	%io:format("~p~n",[User#users.money]),
	%io:format("amount*price:~p, user money: ~p~n", [(Amount*Price ), (User#users.money)]),
	if ((Amount*Price )=< User#users.money)->
		true;
	((Amount*Price) > User#users.money)-> false
end.

%-----------------------------------------------------------------------------------------------------------------%
%---							update_portfolio
%-----------------------------------------------------------------------------------------------------------------%	
update_portfolio(UserID,StockID, Amount, Price, DealType)->
	[User]=do(qlc:q([X||X<-mnesia:table(users),
				 X#users.id == UserID])),
	

	io:format("User update portfolio: ~p ~n" ,[User]),
%% 	io:format("StockID: ~p ~n", [StockID]),
%% 	io:format("Amount: ~p ~n", [Amount]),
%% 	io:format("price: ~p ~n", [Price]),
%% 	io:format("price: ~p ~n", [Price]),
 	io:format("DealType= ~p ~n",[DealType]),
	
	case DealType of
		
		%bid
		0 ->	
				
				%the player that sell stocks
				%maybe more then one record for this stock!!!--> then update total of stocks in stock table in other fun: sub total mybe from more then one reord
				update_stock_table_record_Bid(UserID,StockID,Amount),			
				%update profit -add just profit of this stock  			
					total_profit(UserID),
				%update value -add just value of this stock
					total_value(UserID),
				%update money
					total_money(UserID, Price*Amount);
		1 -> 
			setStockValue(StockID,Price,Amount),%need to do once : evry deal we check 0 and 1 so abitrarrly we put this call here
			io:format("UserId: ~p Buy StockID: ~p  Amount: ~p Price: ~p  ~n", [UserID,StockID,Amount,Price]),
			[StocRec]=do(qlc:q([S||S<-mnesia:table(company_stocks),
				 			S#company_stocks.id == StockID])),
			StockVal = StocRec#company_stocks.current_value,
			io:format("StockVal: ~p  ~n", [StockVal]),
			%if the stock is in favorite we will remove it from this table
			remove_from_favorite(UserID, StockID),
			 % the player that buy stocks
				%take the current value from stock company
			[CurrValue]=do(qlc:q([C||C<-mnesia:table(company_stocks),C#company_stocks.id == StockID])),				
			%io:format("CurrValueeeeeeeeeeeeeeeee ~p ~n",[CurrValue]),			
				%insert to stock table the record-
			Key=get_new_key(stockTableCounter),
			NewStockRecord=#user_stock_table{id=Key,stock_id=StockID,price=Price,total=Amount,user_id=UserID},		
			insert_to_DB(NewStockRecord),			
			total_profit(UserID),
				%update value -add just value of this stock
			total_value(UserID),
				%update money
			total_money(UserID, -Price*Amount)
	end.
		
update_stock_table_record_Bid(StockRecord,Amount)->
	case StockRecord of 
		([H|T])->
			%io:format("Head ~p ~n",[H]),
			%io:format("Amount ~p ~n",[Amount]),
			%io:format("Tail ~p ~n",[T]),
			if (H#user_stock_table.total>Amount)->
		 		%io:format("total>Amount ~n"),
		 		%if total>amount: update this record,
		 		Total=H#user_stock_table.total-Amount,
		 		NewRecord= H#user_stock_table{total=Total},
				%io:format("insert new reord !!!!!!!!!!!!!!! ~p ~n",[NewRecord]),
		 		insert_to_DB(NewRecord);			
	
				(H#user_stock_table.total==Amount)->
				%io:format("total==Amount ~n"),
				%if equal: delet the record,%
				remove_from_db(user_stock_table, H#user_stock_table.id); 
	
				(H#user_stock_table.total<Amount)->
				%io:format("total<Amount ~n"),
		 		%if smaller: delete the record and move to next record with:amount-total to update
				NewAmount=Amount-H#user_stock_table.total,
				remove_from_db(user_stock_table, H#user_stock_table.id),
				update_stock_table_record_Bid(T,NewAmount)
			end;
		([H|[]])->ok;
		([])->ok
	end.
update_stock_table_record_Bid(UserID,StockID,Amount)->%take the all records of this stock
	StockRecords=do(qlc:q([S||S<-mnesia:table(user_stock_table),S#user_stock_table.stock_id == StockID,
							  S#user_stock_table.user_id == UserID])),
	%io:format("Recordes: ~p ~p ~n",[StockRecords,StockID]),
		%sub amount from first record-> 
						%if total>amount: update this record, 
						%if equal: delet the record,%
						%if smaller: sub, delete the record and move to next record with:amount-total to update
	update_stock_table_record_Bid(StockRecords,Amount).
					
%-----------------------------------------------------------------------------------------------------------------%
%---									insert_to_DB
%-----------------------------------------------------------------------------------------------------------------%	
insert_to_DB(Record) ->
    
    Fun = fun() ->
                  mnesia:write(Record)
                                
          end,
    mnesia:transaction(Fun).

%-----------------------------------------------------------------------------------------------------------------%
%---								remove_from_db
%-----------------------------------------------------------------------------------------------------------------%
remove_from_db(Tab,Id) ->
	%io:format("removimg from ~p id: ~p~n",[Tab,Id]),
	Fun = fun()->
				  mnesia:delete(Tab,Id,write)
		  end,
	mnesia:transaction(Fun).

%-----------------------------------------------------------------------------------------------------------------%
%---									total_money
%-----------------------------------------------------------------------------------------------------------------%	
total_money(UserId,Money)->
	[User]=do(qlc:q([X||X<-mnesia:table(users),
				 X#users.id == UserId])),
	
	TotalMoney = User#users{money=User#users.money+Money},
	insert_to_DB(TotalMoney).

%-----------------------------------------------------------------------------------------------------------------%
%---							total_value																					   ---%
%-----------------------------------------------------------------------------------------------------------------%		
%totalValue =sigma[currentVal*amount]+money
%todo: maybe need to change every day
total_value(UserId,StockId,Id)->
	[User]=do(qlc:q([X||X<-mnesia:table(users),X#users.id == UserId])),
	%io:format("User ~p ~n",[User]),
	[StockRecord]=do(qlc:q([Y||Y<-mnesia:table(user_stock_table),
			 Y#user_stock_table.user_id == UserId,Y#user_stock_table.id == Id])),
	
	[Company]= do(qlc:q([C||C<-mnesia:table(company_stocks),C#company_stocks.id==StockRecord#user_stock_table.stock_id])),
	CurrVal = Company#company_stocks.current_value,
	
	%io:format("StockTable record ~p ~n",[StockRecord]),
	%io:format("current_value ~p ~n",[StockRecord#user_stock_table.current_value]),
	%io:format("total ~p ~n",[StockRecord#user_stock_table.total]),
	%io:format("value old ~p ~n",[User#users.value]),
	Value=(CurrVal)*(StockRecord#user_stock_table.total)+(User#users.value),
	%io:format("Value new ~p ~n",[Value]),
	TotalValue = User#users{value=((CurrVal)*(StockRecord#user_stock_table.total)
							  +(User#users.value))},
	%io:format("Value new ~p ~n",[TotalValue]),
	insert_to_DB(TotalValue).

total_valueList([H|T])->total_value(H#user_stock_table.user_id,H#user_stock_table.stock_id,H#user_stock_table.id),
			   %io:format("total value for ~p ~n",[H]),
			   total_valueList(T);
total_valueList([])->ok.	


total_value(UserId)->
	%io:format("0 ~p ~n",[UserId]),
	[User]=do(qlc:q([U||U<-mnesia:table(users),U#users.id == UserId])),	
	InitUser = User#users{value=0},
	insert_to_DB(InitUser),	
	StockTable=do(qlc:q([Y||Y<-mnesia:table(user_stock_table),
			 Y#user_stock_table.user_id == UserId])),
	total_valueList(StockTable).


	
  
%-----------------------------------------------------------------------------------------------------------------%
%---										total_profit
%-----------------------------------------------------------------------------------------------------------------%	
%%profit= [currentVal-BuyingPrice]/[buyingprice/100]
%totalprofit = sigma[(currentVal-BuyingPrice)*amount]
total_profitId(UserId,StockId,RecordId)->
	
	[User]=do(qlc:q([X||X<-mnesia:table(users),X#users.id == UserId])),
	%io:format("User ~p~n", [User]),
	[StockRecord]=do(qlc:q([Y||Y<-mnesia:table(user_stock_table),
			 Y#user_stock_table.user_id == UserId,Y#user_stock_table.stock_id == StockId,Y#user_stock_table.id==RecordId])),
	%io:format("StockRecord ~p~n", [StockRecord]),
	
	[Company]= do(qlc:q([C||C<-mnesia:table(company_stocks),C#company_stocks.id==StockRecord#user_stock_table.stock_id])),
	CurrVal = Company#company_stocks.current_value,
	

			Sub = (CurrVal-StockRecord#user_stock_table.price),
 			%io:format("Sub ~p~n", [Sub]),
 			Total= StockRecord#user_stock_table.total,
 			%io:format("Total ~p~n", [Total]),
 			Profit = User#users.profit,
			%io:format("Profit ~p~n", [Profit]),
			TotalProfit = (Sub*Total+Profit),
			%io:format("TotalProfit ~p~n", [TotalProfit]),	
			NewProfit = User#users{profit=(TotalProfit)},
			%io:format("TotalProfit ~p~n", [NewProfit]),	
			insert_to_DB(NewProfit).


total_profitList([H|T])->
				%io:format("total profit for: ~p ~n",[H]),
				total_profitId(H#user_stock_table.user_id,H#user_stock_table.stock_id,H#user_stock_table.id),
				%io:format("NEXT total profit for: ~p ~n",[T]),		   
			    total_profitList(T);
total_profitList([])->ok.	


total_profit(UserId)->

	[User]=do(qlc:q([U||U<-mnesia:table(users),U#users.id == UserId])),	
	InitUser = User#users{profit=0},
	insert_to_DB(InitUser),	
	StockTable=do(qlc:q([Y||Y<-mnesia:table(user_stock_table),
			 Y#user_stock_table.user_id == UserId])),
	%io:format("StockTable: ~p ~n",[StockTable]),
	total_profitList(StockTable).


	
%-----------------------------------------------------------------------------------------------------------------%
%---						get_new_key
%-----------------------------------------------------------------------------------------------------------------%
get_new_key(CounterName)->
	[Counter]=do(qlc:q([X||X<-mnesia:table(counters),X#counters.name == CounterName])),
	Value= Counter#counters.value,
	NewCounter=Counter#counters{value=Value+1},
	insert_to_DB(NewCounter),
	Value.

%-----------------------------------------------------------------------------------------------------------------%
%---					    	Do				
%-----------------------------------------------------------------------------------------------------------------%
do(Q) ->
    F = fun() -> qlc:e(Q) end,
    {atomic, Val} = mnesia:transaction(F),
    Val.
%-----------------------------------------------------------------------------------------------------------------%
%---																										   ---%
%-----------------------------------------------------------------------------------------------------------------%

tN()->ok.


t()-> 
	  
	total_profit(1),
  	 total_profit(2),
	 total_profit(3),
  	 total_value(1),
  	 total_value(2),
 	 total_value(3),
 	 tN().
